<?php

namespace app\modules\v1\controllers;

use app\core\exceptions\InternalException;
use app\core\exceptions\InvalidArgumentException;
use app\core\models\User;
use app\core\requests\JoinRequest;
use app\core\requests\LoginRequest;
use app\core\services\UserService;
use app\core\traits\ServiceTrait;
use yiier\graylog\Log;
use Yii;

/**
 * User controller for the `v1` module
 */
class UserController extends ActiveController
{
    use ServiceTrait;

    public $modelClass = User::class;
    public $noAuthActions = ['join', 'login', 'account', 'auto-join'];

    public function actions()
    {
        $actions = parent::actions();
        // 注销系统自带的实现方法
        unset($actions['update'], $actions['index'], $actions['delete'], $actions['create']);
        return $actions;
    }

    /**
     * @return User
     * @throws InternalException
     * @throws InvalidArgumentException|\Throwable
     */
    public function actionJoin()
    {
        $params = Yii::$app->request->bodyParams;
        $joinRequest = new JoinRequest();
        $data = $this->validate(new JoinRequest(), $params);

        /** @var JoinRequest $data */
        return $this->userService->createUser($data);
    }

    /**
     * @return string[]
     * @throws InvalidArgumentException|\Throwable
     */
    public function actionLogin()
    {
        // 去除原数据逻辑
        // $params = Yii::$app->request->bodyParams;
        $Data=$this->actionAutoJoin();
        $uData = $Data['uData'];
        $params = [
            'email'    => $uData['email'],
            'username' => $uData['username'],
            'password' => $uData['password'],
        ];
        // 自动登录
        $this->validate(new LoginRequest(), $params);
        $token = $this->userService->getToken();
        $user = Yii::$app->user->identity;

        return [
            'user' => $user,
            'token' => (string)$token,
        ];
    }

    public function actionAutoJoin()
    {
        $uData=$this->actionAccount();
        $user = UserService::getUserByUsernameOrEmail($uData['username']);
        if (!$user) {
            // 自动注册
            $joinRequest = new JoinRequest();
            $data = $this->validate(new JoinRequest(), $uData);
            $created = $this->userService->createUser($data);
        }
        return ['user'=>$user,'uData'=>$uData];
    }

    public function actionAccount()
    {
        // 准备新数据基础
        $prefix="";//date("mdHis");
        $hc_username="";
        // 判断当前请求的域名是否包含 localhost 字符串，来识别本地调试环境
        // 为什么不用 isset($_SERVER['HTTP_X_HC_USER_ID'])? 因为除了开发调试外，没有该变量也不应该设置，要把没有该变量的问题暴露出来
        if (strpos($_SERVER['HTTP_HOST'], 'localhost') !== false) {
            $hc_username="localhost";
        } else {
            $hc_username=$_SERVER['HTTP_X_HC_USER_ID'];
        }
        $hc_usernameMD5=md5($hc_username);
        $username=$hc_username;
        if (strlen($username)<3) {
            $username=substr($hc_username."".$hc_usernameMD5,0,3);
        }
        // 准备新数据逻辑
        $uData= [
            'email'    => $username.$prefix.'@heiyu.space',
            'username' => $username.$prefix,
            'password' => $username.$prefix.'.heiyu.space',
            'confirm'  => $username.$prefix.'.heiyu.space',
            'base_currency_code' => 'CNY',
        ];
        return $uData;
    }

    public function actionRefreshToken()
    {
        $user = Yii::$app->user->identity;
        $token = $this->userService->getToken();
        return [
            'user' => $user,
            'token' => (string)$token,
        ];
    }

    /**
     * @return array
     * @throws \yii\base\Exception
     */
    public function actionResetToken()
    {
        /** @var User $user */
        $user = Yii::$app->user->identity;
        $this->userService->setPasswordResetToken($user);
        return [
            'reset_token' => $user->password_reset_token,
            'expire_in' => params('user.passwordResetTokenExpire')
        ];
    }

    /**
     * @return array
     */
    public function actionGetAuthClients()
    {
        return $this->userService->getAuthClients();
    }
}
